package com.neugh.controller;


import com.alicom.dysms.api.SmsDemo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mysql.cj.x.protobuf.MysqlxCrud;
import com.neugh.entity.*;
import com.neugh.service.*;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author sot
 * @since 2020-05-15
 */
@Controller
public class UserController {

    @Autowired
    UserService userService;

    @RequestMapping("/dologin")
    public String dologin(){
        return "login";
    }


    @RequestMapping("/myinfo")
    public String myinfo(Model moedl,HttpSession session){
        User user = (User) session.getAttribute("user");
        String n=houService.selecHou(user.getUserId());
        if(n==null){
            n="未认证";
        }
        moedl.addAttribute("shou",n);
        return "myinfo";
    }

    @RequestMapping("/means")
    public String means(){
        return "means";
    }

    @Autowired
    HomeService homeService;

    @Autowired
    HouService houService;


    @Autowired
    HouseService houseService;

    @Autowired
    CollectService collectService;

    @Autowired
    RepairService repairService;

    @Autowired
    RealService realService;

    @Autowired
    OrdeService ordeService;

    @Autowired
    ShopService shopService;

    @Autowired
    CommService commService;

    @Autowired
    GiveService giveService;

    /**
     * 登录
     * @param userPhone
     * @param userPassword
     * @param session
     * @param model
     * @return
     */
    @RequestMapping("/login")
    public String login(String userPhone, String userPassword,HttpSession session, Model model){
        //判断账号密码输入格式是否正确
        //给密码进行加密
        Subject subject= SecurityUtils.getSubject();
        UsernamePasswordToken token=new UsernamePasswordToken(userPhone, userPassword);

        try {
            User user=userService.getOne(new QueryWrapper<User>().eq(User.USERPHONE, userPhone));
            session.setAttribute("user", user);
            subject.login(token);
            return "redirect:myinfo";
        }catch(UnknownAccountException e){
            //没有该账号
            model.addAttribute("error", "没有该账号");

        }catch(IncorrectCredentialsException e){
            //密码错误
            model.addAttribute("error", "密码错误");
        } catch (Exception e) {
            model.addAttribute("error", "登录失败");
        }
        return "login";
    }

    @RequestMapping("/doregister")
    public String doregister(){
        return "register";
    }

    /**
     * 注册
     * @param userPhone
     * @param userPassword
     * @return
     */
    @RequestMapping("/insregister")
    public String insregister(String userPhone,String userPassword){
        boolean n=userService.addUser(userPhone,userPassword);

        if(n){
            return "redirect:login";
        }
        return "doregister";
    }


    //手机短信
    @RequestMapping("/send")
    public void send(String phone){
        int num=(int)((Math.random()*9.0D+1.0D)*100000.0D);
        String i=String.valueOf(num);
        SmsDemo sms=new SmsDemo();
        sms.testOne(i,phone);
        System.out.println(phone);

    }

    @RequestMapping("/domyinfo")
    public String domyinfo(Integer userId,Model model){
        model.addAttribute("user",userService.getById(userId));
        return "myinfo";
    }

    //添加用户信息
    @RequestMapping("/select")
    public String select(User user,Model model){
        model.addAttribute("user",userService.save(user));
        return "means";
    }

    //根据id查询
    @RequestMapping("/seleUser")
    public String seleUser(Integer userId,Model model){
        model.addAttribute("seleuser",userService.getById(userId));
        return "means";
    }

    @RequestMapping("/doname")
    public String doname(Integer userId,Model model){
        User user=userService.getById(userId);
        model.addAttribute("seleuser",user);
        return "updnickname";
    }

    //修改
    @RequestMapping("/upname")
    public String upname(User user,Integer userId,Model model){
        boolean n=userService.updateById(user);
        if(n){
            return "redirect:seleUser?userId="+userId;
        }

        return "redirect:doname?userId="+user.getUserId();
    }


    @RequestMapping("/dohou")
    public String dohouse(){
        return "house";
    }

    @RequestMapping("/hou")
    public String hou(Hou hou, Model model){
       hou.setAuditStatus("已认证");
       boolean h=houService.save(hou);
       if(h){
           return "redirect:myinfo";
       }
       return "hou";
    }


    @RequestMapping("/doserve")
    public String serve(){
        return "serve";
    }

    @RequestMapping("/doperiphery")
    public String doperiphery(){
        return "periphery";
    }


  //查询周边商家
   @RequestMapping("/selneigh")
    public String selneigh(Home home, Model model){
       List<Home> homeList=homeService.slectList(home);
       model.addAttribute("homeList",homeList);
       return "neigh";
    }

    //根据id查询周边商家
    @RequestMapping("/slelHome")
    public String slelHome(Integer homeId,Model model){

        model.addAttribute("seleList",homeService.selecHomeId(homeId));
        return "neigh-next";
    }


    //查询租房信息
    @RequestMapping("/dozufang")
    public String dozufang(String condition, Model model) {
        String houseTitle=condition;
        String houseType=condition;
        String houseTurn=condition;
        //List<House> houseList = houseService.seleHouse(house);
        List<House> houseList=houseService.houseByTile(houseTitle,houseTurn,houseType);
        model.addAttribute("houseList", houseList);
        for (House house : houseList) {
            System.out.println(house.getHouseTitle());
        }
        return "zufang";
    }

    @RequestMapping("/sleHouse")
    public String sleHouse(Integer houseId,Model model){
        model.addAttribute("selhList",houseService.seleHouseById(houseId));
        return "zufang-one";
    }

    //关注房租信息  收藏
    @RequestMapping("/addZu")
    public String addZu(Integer houseId,Integer userId,Model model,HttpSession session){
        User user = (User) session.getAttribute("user");
        model.addAttribute("",collectService.addCollect(houseId,userId));
        return "redirect:sleHouse";
    }

    @RequestMapping("/keepList")
    public String keepList(Model model,HttpSession session){
        User user=(User) session.getAttribute("user");
        List<House> collectList=collectService.selectList(user.getUserId());
        model.addAttribute("collectList",collectList);
        return "keep";
    }


    //跳转道维修页面
    @RequestMapping("/doappeal")
    public String doappeal(){
        return "appeal";
    }

    //维修
    @RequestMapping("/upload")
    public String upload(@RequestParam("repairImg") MultipartFile repairImg, @RequestParam("repairtContent") String repairtContent,Model model,HttpSession session) {
        User user = (User) session.getAttribute("user");
        if(repairImg.isEmpty()){
            return "doappeal";
        }

        String orignalFilename= repairImg.getOriginalFilename(); //获取文件名
        //获取文件后缀
        String suffix=orignalFilename.substring(orignalFilename.lastIndexOf("."));
        //新的名字，防止重复存数据库的名字
        String newFilename="jvbao_"+ UUID.randomUUID().toString()+suffix;
        File file1=new File("D:\\ider\\cangku\\neughlinlibang\\Neugh\\itcy\\src\\main\\resources\\static\\img\\"+newFilename);

        try {
            repairImg.transferTo(file1);
            boolean f =repairService.addRep(repairtContent,newFilename,user.getUserId());
            if(f){
                return "redirect:doserve";
            }

        }catch (IOException e){
            e.printStackTrace();
        }
        return "doappeal";
    }

    //跳转物业缴费页面
    @RequestMapping("/dojiaofei")
    public String dojiaofei(Integer userId,HttpSession session,Model model){
        model.addAttribute("reaList",realService.seleReaList(userId));
        return "jiaofei";
    }

    @RequestMapping("/domobel")
    public String domobel(Integer userId,HttpSession session,Model model){

      //  model.addAttribute("orderList",ordeService.seleOrde(userId));
        return "mobile";
    }

    //物业缴费
    @RequestMapping("/wuye")
    public String wuye(Model model,HttpSession session){
     //   Real real=new Real();
        User user=(User)session.getAttribute("user");
        Integer userId=user.getUserId();
        //real.setUserId(userId);
        double realFee=(Double) session.getAttribute("realBille");
        double realPrick= (Double) session.getAttribute("totall");
        double realWater=(Double) session.getAttribute("realWatere");
        double realBill=(Double)session.getAttribute("realFee");
        realService.addRel(realFee,realBill,realWater,realPrick,userId);
        //System.out.println();
        return "redirect:doserve";
    }

    //添加手机订单
    @RequestMapping("/orderadd")
    public String orderadd(Model model,HttpSession session){
        //model.addAttribute("",ordeService.addOrderS(order));
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
        String Date = df.format(new Date());
        Orde order=new Orde();
        User user = (User)session.getAttribute("user");
        Integer userId = user.getUserId();
        order.setUserId(userId);
        order.setOrderNum((String) session.getAttribute("saveorderNum"));
        order.setRPhone((String) session.getAttribute("savePhone"));
        order.setOrderPrice((String) session.getAttribute("savetotal"));
        order.setShopId(-1);
        order.setOrderStatus("支付成功");
        order.setOrderTypeId(2);
        order.setOrderUme(1);
        order.setOrderTime(Date);
      //  order.setOrderTime("2015-4-8");
        ordeService.save(order);
       // this.ordeService.addOrderS(order);

        return "redirect:doserve";
    }


    //跳转首页
    @RequestMapping("/homepage")
    public String homepage(Model model){
        model.addAttribute("eightList",shopService.selectEnightShop());
        model.addAttribute("sixList",shopService.selectSixShop());
        return "homepage";
    }

    //跳转邻里社
    @RequestMapping("/dong")
    public String dong(Model model){
        model.addAttribute("commList",commService.selectAllComm());
        /*
        model.addAttribute("JudgeList",judgeService.selectCommById(commId));*/
        return "dongtai";
    }

   //跳转消息页面
    @RequestMapping("/domymsg")
    public String domymsg(){
        return "mymsg";
    }

    //物业缴费详情
    @RequestMapping("/dojiaofeione")
    public String dojiaofeione(Integer userId,Model model){
        List<Real> realList=realService.selectList(userId);
        model.addAttribute("realList",realList);
        return "jiaofei-one";
    }



    //公告
    @RequestMapping("/dogive")
    public String dogive(){
        return "give";
    }

    @RequestMapping("/giveOid")
    public String giveOid(Integer giveTypeId,Model model){
        model.addAttribute("giveList",giveService.selectId(giveTypeId));
        return "give-one";
    }

    @RequestMapping("/giveOtid")
    public String giveOtid(Integer giveTypeId,Model model){
        model.addAttribute("giveList",giveService.selectId(giveTypeId));
        return "give-one1";
    }

    @RequestMapping("/givetid")
    public String givetid(Integer giveId,Model model,String giveContent){

        String [] imgs = giveContent.split(",");

        List<String> imgList = new ArrayList<String>();
        for(int i = 0;i<imgs.length;i++){
            imgList.add(imgs[i]);
        }
        model.addAttribute("imgList",imgList);
        model.addAttribute("giveList",giveService.seleTyId(giveId));
        return "give-two";
    }

    @RequestMapping("/givettid")
    public String givettid(Integer giveId,Model model,String giveContent){

        String [] imgs = giveContent.split(",");

        List<String> imgList = new ArrayList<String>();
        for(int i = 0;i<imgs.length;i++){
            imgList.add(imgs[i]);
        }
        model.addAttribute("imgList",imgList);
        model.addAttribute("giveList",giveService.seleTyId(giveId));
        return "give-two1";
    }


    //维修详情
    @RequestMapping("/seleappOne")
    public String seleappOne(Integer userId,Model model){
        model.addAttribute("reapList",repairService.selRepair(userId));
        return "appeal-one";
    }
}